<template>
  <div>

    <!-- 顶部按钮 -->
    <div class="card" style="margin-bottom: 8px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 瀑布流卡片 -->
    <div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" class="card-grid">
      <div
          v-for="item in data.tableData"
          :key="item.id"
          class="card-item"
          :class="{ checked: data.ids.includes(item.id) }"
          @click="toggleSelect(item)"
      >
        <el-image
            v-if="item.avatar"
            :src="item.avatar"
            fit="cover"
            class="card-img"
            :preview-src-list="[item.avatar]"
            preview-teleported
        />
        <div v-else class="no-img">暂无头像</div>

        <div class="card-body">
          <span class="card-time">{{ item.createTime }}</span>
          <div class="card-actions">
            <el-button type="primary" circle :icon="Edit" @click.stop="handleEdit(item)"/>
            <el-button type="danger" circle :icon="Delete" @click.stop="del(item.id)"/>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载提示 -->
    <div v-if="busy" class="loading-tip">加载中...</div>

    <!-- 上传弹窗（与原来一致） -->
    <el-dialog title="头像信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="avatar" label="头像">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 20,          // 瀑布流一次多拿点
  total: 0,
  ids: [],
  busy: false            // 无限滚动锁
});

/* 首次加载 */
const load = () => {
  request.get('/avatar/selectPage', {
    params: {pageNum: 1, pageSize: data.pageSize}
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
      data.pageNum = 1;
    }
  });
};

/* 滚动到底部继续加载 */
const loadMore = () => {
  if (data.busy || data.tableData.length >= data.total) return;
  data.busy = true;
  request.get('/avatar/selectPage', {
    params: {pageNum: ++data.pageNum, pageSize: data.pageSize}
  }).then(res => {
    if (res.code === '200') {
      data.tableData.push(...res.data.list);
    }
    data.busy = false;
  });
};

/* 点击卡片多选 / 取消 */
const toggleSelect = (item) => {
  const idx = data.ids.indexOf(item.id);
  idx > -1 ? data.ids.splice(idx, 1) : data.ids.push(item.id);
};

/* 其余方法（新增、编辑、删除、上传回调）与原逻辑保持一致 */
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
};
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};
const save = () => {
  const method = data.form.id ? 'put' : 'post';
  const url = data.form.id ? '/avatar/update' : '/avatar/add';
  request({url, method, data: data.form}).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();            // 重新拉取第一页
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，确定吗？', '提示', {type: 'warning'})
      .then(() => request.delete('/avatar/delete/' + id))
      .then(res => {
        if (res.code === '200') {
          ElMessage.success('删除成功');
          load();
        }
      });
};
const delBatch = () => {
  if (!data.ids.length) return ElMessage.warning('请先选择');
  ElMessageBox.confirm('批量删除后无法恢复，确定吗？', '提示', {type: 'warning'})
      .then(() => request.delete('/avatar/delete/batch', {data: data.ids}))
      .then(res => {
        if (res.code === '200') {
          ElMessage.success('删除成功');
          load();
        }
      });
};
const handleFileUpload = (res) => {
  data.form.avatar = res.data;
};

load();
</script>

<style scoped>
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.card-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: transform .2s, box-shadow .2s;
  cursor: pointer;
}

.card-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, .15);
}

.card-item.checked {
  outline: 2px solid #409eff;
}

.card-img {
  width: 100%;
  height: 200px;
  display: block;
}

.no-img {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
}

.card-body {
  padding: 8px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-time {
  font-size: 12px;
  color: #666;
}

.card-actions {
  display: flex;
  gap: 6px;
}

.loading-tip {
  text-align: center;
  padding: 12px;
  color: #999;
}
</style>